package com.ibm.dw.open18;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

import org.appfuse.service.GenericManager;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.datamodel.DataModelSelection;
import org.jboss.seam.faces.FacesMessages;   

@Name( "courseAction" )
@Scope( ScopeType.CONVERSATION )
public class CourseAction implements Serializable {

	private static final long serialVersionUID = 1L;

	@In( "#{courseManager}" )
	private GenericManager<Course, Long> courseManager;

	@DataModel
	private List<Course> courses;

	@DataModelSelection
	@In( value = "course", required = false )
	@Out( value = "course", required = false )
	private Course selectedCourse;

	@Begin( join = true )
	@Factory( "courses" )
	public void findCourses() {
		System.out.println( "Retrieving courses..." );
		courses = courseManager.getAll();
		Collections.sort( courses );
	}

	public String selectCourse() {
		System.out.println( "Selected course: " + selectedCourse.getName() );
		System.out.println( "Redirecting to /courses.xhtml" );
		return "/courses.xhtml";
	}

	public String showCourses() {
		selectedCourse = null;
		return "/courses.xhtml";
	}

	public String deleteCourse() {
		courseManager.remove( selectedCourse.getId() );
		courses.remove( selectedCourse );
		FacesMessages.instance().add( selectedCourse.getName() + " has been removed." );
		// clear selected course so that it is not displayed in the detail pane
		selectedCourse = null;
		return "/courses.xhtml";
	}

	public String addCourse() {
		selectedCourse = new Course();
		selectedCourse.setAddress( new Address() );
		return "/courseEditor.xhtml";
	}

	public String editCourse() {
		selectedCourse = courseManager.get( selectedCourse.getId() );
		return "/courseEditor.xhtml";
	}

	public String saveCourse() {
		// remove from cached list
		if ( selectedCourse.getId() != 0 ) {
			courses.remove( selectedCourse );
		}
		courseManager.save( selectedCourse );
		// add to cached list
		courses.add( selectedCourse );
		Collections.sort( courses );
		FacesMessages.instance().add( "#{course.name} has been saved." );
		return "/courses.xhtml";
	}

	public String clearSelection() {
		selectedCourse = null;
		return "/courses.xhtml";
	}
}
